package com.jd.charactercalculator.util;



import java.lang.reflect.Field;
import java.util.HashMap;

/**
 * object对象转换为map
 *
 * @author: 杨晓鹏
 * @since: 12-7-24 上午11:12
 * @version: 1.0.0
 */
public class ObjectUtils {

    /**
     * 将指定对象属性名称和属性值转化为Map键值对
     *
     * @param obj
     * @return
     */
    public static HashMap<String, Object> objectToMap(Object obj){

        if (obj == null) {
            throw new RuntimeException("对象为空"
            );
        }

        Class clazz = obj.getClass();
        HashMap<String, Object> map = new HashMap<String, Object>();
        getClass(clazz, map, obj);
        return map;
    }

    /**
     * 取得属相，并放到map中
     */
    private static void getClass(Class clazz, HashMap<String, Object> map, Object obj){
        if (clazz.getSimpleName().equals("Object")) {
            return;
        }

        //取得所有字段，包括公共、保护、默认（包）访问和私有字段 ，但是不包含集成的地段
        Field[] fields = clazz.getDeclaredFields();
        if (fields == null || fields.length <= 0) {
            throw new RuntimeException("当前对象中没有任何属性值");
        }

        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);
            String name = fields[i].getName();
            Object value = null;
            try {
                value = fields[i].get(obj);
            } catch (IllegalAccessException e) {
                throw new RuntimeException();
            }
            map.put(name, value);

        }
        //取得父类的字段
        Class superClzz = clazz.getSuperclass();
        getClass(superClzz, map, obj);
    }

}
